def make_life_script(job_dir_path: str, logs_dir_path: str) -> str:
    return f"""#!/bin/bash
        job_dir_path={job_dir_path}
        logs_dir_path={logs_dir_path}
        cd $job_dir_path
  
        echo 'Command launching' >&2
        echo "job_dir_path=$job_dir_path" >&2
        echo "logs_dir_path=$logs_dir_path" >&2
        echo '-----------------' >&2
        ./command.sh &
        pid=$!
        echo $pid > $logs_dir_path/pid.txt
  
        wait $pid
        exitcode=$?
        echo '-----------------'  >&2
        echo "Command finished (exit code: $exitcode)" >&2
        echo $exitcode > $logs_dir_path/exitcode.txt;
        rm -f $logs_dir_path/pid.txt
  
        echo 'Releasing' >&2
        ./release.sh"""


def make_check_script(job_dir_path: str, logs_dir_path: str) -> str:
    return f"""#!/bin/bash
        job_dir_path={job_dir_path}
        logs_dir_path={logs_dir_path}
        cd $job_dir_path
        
        if [ -f $logs_dir_path/exitcode.txt ]; then
            echo "STOPPED"
        else 
            echo "RUNNING"
        fi
        """


def make_monitor_script(job_dir_path: str, logs_dir_path: str) -> str:
    return f"""#!/bin/bash
        job_dir_path={job_dir_path}
        logs_dir_path={logs_dir_path}
        cd $job_dir_path
        
        touch $logs_dir_path/stdout.txt
        touch $logs_dir_path/stderr.txt
        
        echo 'Monitoring started' >&2
        echo '------------------' >&2
        tail -f $logs_dir_path/stdout.txt     &
        stdout_pid=$!
        tail -f $logs_dir_path/stderr.txt >&2 &
        stderr_pid=$!
        
        sleep 1
        while [ ! -f $logs_dir_path/exitcode.txt ]; do
          sleep 1
        done
        exitcode=$(cat $logs_dir_path/exitcode.txt)
        
        kill $stdout_pid
        kill $stderr_pid
        
        echo '------------------' >&2
        echo 'Monitoring stopped' >&2
        exit $exitcode
        """


def make_terminate_script(job_dir_path: str, logs_dir_path: str) -> str:
    return f"""#!/bin/bash
        job_dir_path={job_dir_path}
        logs_dir_path={logs_dir_path}
        cd $job_dir_path
        
        echo 'Terminating' >&2
        echo '------------------' >&2
        if [ -f $logs_dir_path/pid.txt ]; then
          pid=$(cat $logs_dir_path/pid.txt)
          echo "Killing pid $pid" >&2
          kill $pid
          rm -f $logs_dir_path/pid.txt
        else 
          echo "No pid.txt found" >&2
        fi
        """
